package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Utils {
    public static WebDriver webDriver;

    /**
     * 创建 webDriver 并 访问指定 url
     * @param url
     */
    public Utils(String url) {
        if (null == webDriver) {
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            // 允许访问所有连接
            options.addArguments("--remote-allow-origins=*");
            this.webDriver = new EdgeDriver(options);
            // 隐式等待 3 秒
            this.webDriver.manage().timeouts().implicitlyWait(java.time.Duration.ofSeconds(3));
        }
        webDriver.get(url);
    }

    /**
     * 关闭 WebDriver 和浏览器
     */
    public void closeBrowser() {
        if (webDriver != null) {
            webDriver.quit();
        }
    }

    /**
     * 进行屏幕截图并将其保存到自定路径
     * 路径: ./src/tests/image/2025-2-24/LoginPage-17548130.png
     * @param str
     */
    public void getScreenShot(String str) {
        try {
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmssSS");

            String dirTime = dateFormatter.format(LocalDateTime.now());
            String fileTime = timeFormatter.format(LocalDateTime.now());
            // 使用 File.separator 来适应不同操作系统上的路径分隔符
            String filename = "src" + File.separator + "test" + File.separator + "image" + File.separator + dirTime + File.separator + str + "-" + fileTime + ".png";
            // 创建目录
            Path path = Paths.get(filename).getParent();
            if (path != null && !Files.exists(path)) {
                Files.createDirectories(path);
            }
            // 将截图存放到指定位置
            File srcFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
            File destFile = new File(filename);
            FileUtils.copyFile(srcFile, destFile);
        } catch (IOException e) {
            // 更好的错误处理或日志记录
            System.err.println("截图失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
